package geguol.cc.widgetapplication.feature;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 作者  格锅
 * 时间  2017/6/5 16:33
 * 文件  WidgetApplication
 * 描述  可暂停的线程池
 * 思路：对在线程开始前加锁，锁住执行方法
 */

public class PasusableThreadPoolExecutor extends ThreadPoolExecutor {
	private boolean isPaused ;
	private ReentrantLock pauseLock = new ReentrantLock();
	Condition unpaused = pauseLock.newCondition();// 操作状态

	public PasusableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
		super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
	}

	@Override
	protected void beforeExecute(Thread t, Runnable r) {
		super.beforeExecute(t, r);
//		if (pauseLock.tryLock()) 如果锁可用则获取该锁
		/**
		 * 这里是控制的是线程执行之前的操作
		 * 并不是线程在执行过程中进行暂停
		 * */
		pauseLock.lock();
		try {
			// 如果暂停了 这里一直等待
			// await 不是线程阻塞的
			while (isPaused) unpaused.await();
		} catch (InterruptedException e) {
//			e.printStackTrace();
			t.interrupt();// 等待失败 就唤醒
		} finally {
//			锁必须释放
			pauseLock.unlock();
		}

	}

	public void pause() {
		pauseLock.lock();
		try {
			isPaused = true;
		} finally {
			pauseLock.unlock();
		}
	}

	public void resume() {
		pauseLock.lock();
		try {
			isPaused = false;
			unpaused.signalAll();
		} finally {
			pauseLock.unlock();
		}
	}
}
